# -*- coding: utf-8 -*-

from db.mysql import MysqlClient
from common.config import *
from itertools import product
from common.helper import Helper
import asyncio, aiohttp
from urllib.parse import urlencode
import json


class Spider(object):
    def __init__(self):
        self.name = "i康保·综合意外"
        self.mysql = MysqlClient()

    def genProductInfo(self):
        plan = {
            "year": ["18-60", "61-65"],
            "days": ["1y"],
            "people_count": ['1'],
            "money": ["300000", "500000"],
            "socialSec": ["Y", "N"]
        }
        for v in product(plan["year"], plan["days"], plan["people_count"], plan["money"], plan["socialSec"]):
            data = Helper.formatProductInfo(plan, v)
            yield data

    # 爬虫
    async def requestJson(self, dt):
        params = '''
        gender: M
        benLevel: 05
        coverageAmount: 300000
        personAge: 62
        coverageUnits: 300
        socialSecurity: Y
        '''
        data = Helper.perfectJson(params)
        data["coverageAmount"] = dt["money"]
        data["socialSecurity"] = dt["socialSec"]
        data["personAge"] = "19" if dt["year"] == "18-60" else "62"
        data["coverageUnits"] = "300" if dt["money"] == "300000" else "500"
        payload = urlencode(data).replace("+", "")
        async with aiohttp.ClientSession() as session:
            async with session.post(url=domain[self.name]["url"], headers=domain[self.name]["header"],
                                    data=payload) as resp:
                res = await resp.text()
                if "totalPrem" in res:
                    price = Helper.decimalParse(json.loads(res)["totalPrem"])
                    data={
                        "name":self.name,
                        "company":"平安保险",
                        "price":price
                    }
                    data.update( dt )
                    Helper.mergeTable( self.name,self.mysql,data )

    def asyncTask(self):
        tasks = [self.requestJson(data) for data in self.genProductInfo()]
        event_loop = asyncio.get_event_loop()
        event_loop.run_until_complete(asyncio.gather(*tasks))
        event_loop.close()
